package com.joyoung.sdk;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hiflying.smartlink.OnSmartLinkListener;
import com.hiflying.smartlink.SmartLinkedModule;
import com.joyoung.sdk.interface_sdk.CallBack;
import com.joyoung.sdk.interface_sdk.ChangeDevCallBack;
import com.joyoung.sdk.interface_sdk.SendCmdCallback;
import com.joyoung.sdk.interface_sdk.JoyoungLinkCallBack;
import com.joyoung.sdk.utils.ConfigUdpBroadcast;
import com.joyoung.sdk.utils.JoyoungDMS;
import com.joyoung.sdk.info.ModuleInfo_Sdk;
import com.joyoung.sdk.interface_sdk.CommandCallBack;
import com.joyoung.sdk.utils.JoyoungSDK;
import com.joyoung.sdk.utils.encryptdecryptutil.Encrypt;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_start_dev;
    private Button btn_stop_dev;
    private Button btn_getMydev;
    private Button btn_quer_dev_state;
    private String userName = "18580538191";
    private String passwd = "111111";
    String xxteaKey;

    private static final String TAG = MainActivity.class.getSimpleName();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        xxteaKey = Encrypt.MD5(userName + passwd).substring(0, 16);
        initView();
        try {
            accountLogin(userName, passwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 账号登录
     *
     * @param tel
     * @param password
     */
    private void accountLogin(String tel, final String password) {
        xxteaKey = Encrypt.MD5(tel + password).substring(0, 16);

        new JyHttpDSG1().login(tel, password,
                new JyHttpDSG1.JoyoungCallBack<BaseResult<UserConfirmData>>() {
                    @Override
                    public void Success(BaseResult<UserConfirmData> result) {
                        Log.e("liuwei", result.getData().getAccessToken());
                        if (result.getCode() == 0) {
                            Gson gson = new Gson();
                            String logindata = gson.toJson(result);
                            JoyoungSDK.getInstance().init(MainActivity.this, logindata, userName, password, "1", commsCallback, joyoungLinkCallBack);
                        } else {

                        }
                    }

                    @Override
                    public void failed(String msg) {
                        Log.e("msg", msg);
                    }
                });
    }

    private void initView() {
        btn_start_dev = (Button) findViewById(R.id.btn_start_dev);
        btn_stop_dev = (Button) findViewById(R.id.btn_stop_dev);
        btn_getMydev = (Button) findViewById(R.id.getMydev);
        btn_quer_dev_state = (Button) findViewById(R.id.btn_quer_dev_state);
        btn_start_dev.setOnClickListener(this);
        btn_stop_dev.setOnClickListener(this);
        btn_getMydev.setOnClickListener(this);
        btn_quer_dev_state.setOnClickListener(this);
        findViewById(R.id.btn_peiwamg).setOnClickListener(this);
        findViewById(R.id.btn_faxoan).setOnClickListener(this);

    }

    ConfigUdpBroadcast.ConnectCallBack connectCallBack =
            new ConfigUdpBroadcast.ConnectCallBack() {
                @Override
                public void onConnect(ModuleInfo_Sdk moduleInfo) {

                    String sg = moduleInfo.getIp();
                    Log.e("moduleInfo", moduleInfo.getProductType() + "---------" +
                            moduleInfo.getSn() + "---" + sg + "--------" + moduleInfo.getMdcode() +
                            "----------" + moduleInfo.getMac() + "--" + moduleInfo.getWifiModuleNumber()
                            + "----------------" + moduleInfo.getWifiServiceType());
                }

                @Override
                public void onConnectTimeOut() {
                    Toast.makeText(MainActivity.this, "设备发现超时", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onConnectOk() {

                }

                @Override
                public void findFilish() {

                }
            };

    CallBack callBack = new CallBack() {
        @Override
        public void onSuccess() {
//            JoyoungSDK.getInstance().
//                    changeDev(MainActivity.this,"""9217", "d6f1170b533144d78bd76bc571659744", commsCallback);
        }

        @Override
        public void onError() {

        }
    };

    private CommandCallBack commsCallback = new CommandCallBack() {
        @Override
        public void connectionLost(String msg) {
            Log.e(TAG, msg);
        }

        @Override
        public void messageArrived(String topic, String msg) {
            Log.e("返回的指令", topic + "----------------" + msg);
        }

        @Override
        public void deliveryComplete(String token) {

        }
    };

    SendCmdCallback sendCmdCallback = new SendCmdCallback() {
        @Override
        public void onResponse(String msg) {

            Log.e("mqttmsg",msg);
        }

        @Override
        public void onFailure(String error, IOException e) {

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start_dev://启动设备
                try {
                    JoyoungSDK.getInstance().sendCMD(
                            "CC00000000000D00000000B000060001000000000000", "d6f1170b533144d78bd76bc571659744", true, sendCmdCallback);
                    Log.e("msg", "启动设备");
                } catch (Exception e) {
                    e.printStackTrace();

                }
                break;
            case R.id.btn_quer_dev_state://查询设备状态
                try {
                    JoyoungSDK joyoungSDK = JoyoungSDK.getInstance();
                    joyoungSDK.sendCMD(
                            "CC00000000000700000000E800000000", "d6f1170b533144d78bd76bc571659744", sendCmdCallback);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_stop_dev://停止设备
                try {
                    JoyoungSDK joyoungSDK = JoyoungSDK.getInstance();
                    joyoungSDK.sendCMD(
                            "CC00000000000700000000B100000000", "d6f1170b533144d78bd76bc571659744", true, sendCmdCallback);
                    Log.e("msg", "停止设备");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.getMydev://获取设备列表并把appkey赋值给decryptKey

                break;
            case R.id.btn_faxoan://发现设备
                JoyoungDMS.getInstance().deviceDiscovery(MainActivity.this, connectCallBack);
                break;
            case R.id.btn_peiwamg:
                JoyoungDMS.getInstance().deviceDms(MainActivity.this, "jylink", "jylink123",
                        new OnSmartLinkListener() {
                            @Override
                            public void onLinked(SmartLinkedModule smartLinkedModule) {
                                Log.e("smartLinkedModule", smartLinkedModule.getIp() +
                                        "------------" + smartLinkedModule.getMac() +
                                        "-------" + smartLinkedModule.getId());
                            }

                            @Override
                            public void onCompleted() {
                                Log.e("设备配网完成", "");
                            }

                            @Override
                            public void onTimeOut() {
                                Log.e("设备配网超时", "");

                            }
                        });
                break;

        }

    }


    public javax.net.ssl.SSLSocketFactory getSSLContext(Context context, String sslName) {
        // 生成SSLContext对象
        try {
            InputStream inStream = context.getAssets().open(sslName);
            return setCertificates(inStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 从assets中加载证书
        return null;


    }

    public javax.net.ssl.SSLSocketFactory setCertificates(InputStream... certificates) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));

                try {
                    if (certificate != null)
                        certificate.close();
                } catch (IOException e) {
                }
            }

            SSLContext sslContext = SSLContext.getInstance("TLS");

            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());

            trustManagerFactory.init(keyStore);
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            return sslContext.getSocketFactory();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private JoyoungLinkCallBack joyoungLinkCallBack = new JoyoungLinkCallBack() {
        @Override
        public void onSuccess() {
            JoyoungSDK joyoungSDK1 = JoyoungSDK.getInstance();
            joyoungSDK1.changeDev(MainActivity.this, xxteaKey, "18432", "379e548b5ade4afabf29343d2067c348", commsCallback, changeDevCallBack);
        }

        @Override
        public void onError() {

        }
    };

    private ChangeDevCallBack changeDevCallBack = new ChangeDevCallBack() {
        @Override
        public void onSuccess() {
            try {
                JoyoungSDK.getInstance().sendCMD(
                        "CC00000000000D00000000B000060001000000000000", "379e548b5ade4afabf29343d2067c348", true, sendCmdCallback);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError() {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JoyoungSDK.getInstance().onDestroy();
    }
}
